﻿using MediatR;
using MES.Process.API.Application.Command.工序命令;
using MES.Process.Domain;
using MES.Process.Dto;
using MES.Process.ErrorCode;
using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Process.API.Application.CommandHandler.工序命令处理
{
    /// <summary>
    /// 获取工艺所拥有工序命令处理器
    /// </summary>
    public class ProcessCratfsCommandHandler : IRequestHandler<ProcessCratfsCommand, APIResult<List<ProcessByidDto>>>
    {
        private readonly IBaseRepository<Craft_Process> crRepository;
        private readonly IBaseRepository<Processes> processRepository;
        private readonly ILogger<ProcessCratfsCommandHandler> logger;
        public ProcessCratfsCommandHandler(IBaseRepository<Craft_Process> crRepository, IBaseRepository<Processes> processRepository = null, ILogger<ProcessCratfsCommandHandler> logger = null)
        {
            this.crRepository = crRepository;
            this.processRepository = processRepository;
            this.logger = logger;
        }

        public Task<APIResult<List<ProcessByidDto>>> Handle(ProcessCratfsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<List<ProcessByidDto>> result = new APIResult<List<ProcessByidDto>>();
                var list = crRepository.GetValues().AsNoTracking().Where(x => x.CraftsId == request.CraftsId);
                var t= list.Count();
                var res = (from a in list
                           join b in processRepository.GetValues().AsNoTracking()
                          on a.ProcessId equals b.ID
                          select new ProcessByidDto
                          {
                              CraftsId = a.CraftsId,
                              ProcessId = a.ProcessId,
                              StepId = a.StepId,
                              Pid = b.ID,
                              ProcessCode = b.ProcessCode,
                              ProcessName = b.ProcessName,
                              ProcessStatus = b.ProcessStatus,
                              IsImportent = b.IsImportent,
                              PTId = b.PTId,
                              Note = b.Note,
                              ResponsibilityName = b.ResponsibilityName,
                              DepartId = b.DepartId,
                          }).ToList();
                result.Code = APIEnums.Success;
                result.Message = "获取成功";
                result.Data=res;
                return Task.FromResult(result);
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
